package com.owen.util;

import java.io.File;
import java.util.Optional;
import java.util.Properties;
import java.util.logging.Logger;

public class HtmlToPdf {
    //wkhtmltopdf在系统中的路径
    private static String toPdfToolPath = null;
    // 系统配置
    private static Properties application = null;
    // 日志
    private static final Logger logger = Logger.getLogger(HtmlToPdf.class.getName());

    /**
     * html转pdf
     *
     * @param srcPath  html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }

        String[] instructions = new String[9];

        if (toPdfToolPath == null) {
            ApplicationUtil applicationUtil = new ApplicationUtil();
            if (application == null)
                application = applicationUtil.getApplication();

            toPdfToolPath = Optional.ofNullable(application.getProperty("toPdfToolPath")).orElseGet(() ->
                    "wkhtmltopdf"
            );
        }

        instructions[0] = toPdfToolPath;
        instructions[1] = "--header-line";
        instructions[2] = "--header-center";
        instructions[3] = "这里是页眉这里是页眉这里是页眉这里是页眉";
        instructions[4] = "--header-spacing";
        instructions[5] = "10";
        instructions[6] = "http://110.40.156.233:9090/blog/open/post/119";// srcPath
        instructions[7] = "--allow";
        instructions[8] = destPath;
        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(instructions);
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            logger.info(destPath);
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

}
